<?php

namespace app\admin\server\user;

use app\admin\common;
use app\admin\model\user\UserModel;
use app\admin\model\user\UserTypeModel;
use app\admin\model\vip\VipModel;
use app\admin\ServerBase;
use app\admin\validate\user\UserValidate;
use app\logic\model\user\UserScoreLogicModel;
use app\logic\model\user\UserTypeLogicModel;
use app\logic\single\UserScoreSingle;
use think\db\exception\DbException;
use think\exception\ValidateException;
use think\facade\Db;
use think\Request;

class UserServer extends ServerBase
{
    protected $model;
    protected $request;
    /**
     * @var mixed
     */
    protected $param;
    /**
     * @var mixed
     */
    protected $validate;
    /**
     * @var UserTypeModel
     */
    private $typeModel;

    function __construct( Request $request)
    {
        $this->request=$request;
        $this->param=$request->param();
        $this->model=new UserModel();
        $this->validate = new UserValidate();
        $this->typeModel = new UserTypeModel();
        $this->vipModel = new VipModel();
    }

    function getList(){
        [$page,$limit] = $this->getPage($this->param);
        [$list,$count] = $this->model->getList($this->request,[],'*',$page,$limit);
        $type_ids = array_column($list,'type_id');
        $types = UserTypeLogicModel::getByIds($type_ids);
        foreach ($list as &$val){
            $val['type_name'] =$types[$val['type_id']]??'';
            $val['score'] = UserScoreLogicModel::getScoreByUserId($val['id']);
        }
        unset($val);
        $result['data']=$list;
        $result['count']=$count;
        $this->getMessageCode('adminMessage.success.select',2);
        return $result;
    }

    function getDetail(){
        $info = $this->model->getFindById($this->request->param('id'));
        $this->getMessageCode('adminMessage.success.select',2);
        return $info;
    }
    function add(){
        $post = $this->request->post();
        if(!$this->validate->scene('create')->check($post)){
            $this->ERROR = $this->validate->getError();
            return false;
        }
        try {
            if(empty($post['vip_end_time'])){
                $post['vip_end_time'] = null;
            }
            $this->model->save($post);
            $this->getMessageCode('adminMessage.success.insert',2);
            return true;
        }catch (\Error $error){
            $this->ERROR = $error->getMessage();
            return false;
        }catch (DbException $dbException){
            $this->ERROR = $dbException->getMessage();
            return false;
        }
    }
    function edit(){
        $id = $this->request->param('id',0);
        $post = $this->request->post();
        if(empty($post['vip_end_time'])){
            $post['vip_end_time'] = null;
        }
        $post['id'] = $id;
        if(!$this->validate->scene('edit')->check($post)){
            $this->ERROR = $this->validate->getError();
            return false;
        }
        $info  = $this->model->getFindById($id);
        if(empty($info)){
            $this->getMessageCode('adminMessage.error.update',1);
            return false;
        }
        if($info->save($post)){
            $this->getMessageCode('adminMessage.success.update',2);
            return true;
        }else{
            $this->getMessageCode('adminMessage.error.update',1);
            return false;
        }
    }

    function import(){
        if(!request()->file('file')){
            $this->getMessageCode('adminMessage.excel.import.fileTrue',1);
            return false;
        }
        try{
            $res=common::getImportDataFile('public','/');
            $excel_data=common::importData($res['path'],false,1);
        } catch (ValidateException $e) {
            // 验证失败 输出错误信息\
            $this->getMessageCode('adminMessage.excel.import.get_data',1);
            $this->ERROR=$this->error.','.$e->getError();
            return false;
        }
        Db::startTrans();
        try {
            $return =[];
            $insert=[];
            $mobile_arr=[];
            foreach ($excel_data as $key=>$val){
                $return[$key] =[
                    'code'=>1,
                    'msg'=>'成功'
                ];
                $mobile = $val['A']??'';
                if(empty($mobile)){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='用户手机号为空';
                    continue;
                }
                if(strlen($mobile) != 11){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='用户手机号格式错误';
                    continue;
                }
                if(in_array($mobile,$mobile_arr)){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='用户手机号已存在';
                    continue;
                }
                $mobile_arr[] = $mobile;
                $user =UserModel::getInfoByobile($mobile);
                if(!empty($user)){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='用户已存在';
                    continue;
                }
                $vip = $this->vipModel->where('title',$val['B'])->find();
                if(empty($vip)){
                    $vip_id = -1;
                }else{
                    $vip_id = $vip['id'];
                }
                if($vip_id != -1){
                    if($vip['expire_time'] == -1){
                        $vip_end_time = '2099-12-31 23:59:59';
                    }else{
                        $vip_end_time = date('Y-m-d 23:59:59',time() + 86400 * $vip['expire_time']);
                    }
                }
                $nickname = $val['C']??'';
                if(empty($nickname)){
                    $return[$key]['code']=-1;
                    $return[$key]['msg']='用户昵称为空';
                    continue;
                }
                $is_writer = $val['D']??'否';
                $is_writer = $is_writer == '是'?1:-1;
                $type = $this->typeModel->where('title',$val['K'])->find();
                if(!empty($type)){
                    $type_id = $type['type_id'];
                }else{
                    $type_id = 0;
                }
                $insert[]=[
                    'mobile'=>$mobile,
                    'vip_id'=>$vip_id,
                    'vip_end_time'=>$vip_end_time??null,
                    'nickname'=>$nickname,
                    'is_writer'=>$is_writer,
                    'writer_name'=>$val['E']??'',
                    'writer_withdraw_rate'=>$val['F']??'',
                    'true_name'=>$val['G']??'',
                    'writer_sort'=>$val['H']??0,
                    'fans_num'=>$val['I']??0,
                    'writer_mobile'=>$val['J']??0,
                    'type_id'=>$type_id,
                    'order_audit_price'=>$val['L']??0,
                    'create_time'=>date('Y-m-d H:i:s'),
                ];
            }
            if(!empty($insert)){
                $this->model->insertAll($insert);
            }
            $this->getMessageCode('adminMessage.success.insert',2);
            Db::commit();
            return $return;
        }catch (\Exception $exception){
            Db::rollback();
            $this->ERROR=$exception->getMessage();
            return false;
        }
    }

    static function getVipCount($vip_id)
    {
        return UserModel::where('vip_id',$vip_id)->count();
    }
}